package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import com.itheima.utils.QiniuUtils;
import com.itheima.utils.UploadUtils;
import entity.PageResult;
import entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

;import java.util.List;
import java.util.Map;
;import java.util.*;
;

/**
 * @Description:
 * @Author: yp
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Reference
    private RoleService roleService;

    /**
     * 获得用户名【从SpringSecurity里面获得】
     *
     * @return
     */
//    @ApiOperation(value = "获取用户名",httpMethod = "GET")
//    @RequestMapping("/getUserName")
//    public Result getUserName() {
//        try {
//            //1. 获得SecurityContext上下文对象, 获得认证对象, 获得User对象
//            org.springframework.security.core.userdetails.User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            String username = user.getUsername();
//            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
//        }
//    }
    /**
     * 获得用户名【从SpringSecurity里面获得】
     * @return
     */
    @RequestMapping("/getUserName")
    public Result getUserName(){
        try {
            //1. 获得SecurityContext上下文对象, 获得认证对象, 获得User对象
            org.springframework.security.core.userdetails.User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            com.itheima.pojo.User users = userService.findByUsername(username);
            Map map=new HashMap();
            List byUsername2 = userService.findByUsername2(username);
            map.put("username",username);
            map.put("byUsername2",byUsername2);
            map.put("users",users);
            System.out.println(map);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }




    @RequestMapping("/changeUserName")
    public Result changeUserName(@RequestParam int id) {
        try {
            //1. 获得SecurityContext上下文对象, 获得认证对象, 获得User对象
            org.springframework.security.core.userdetails.User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            List list = userService.changeUserName(username, id);
            return new Result(true, "Y", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "N");
        }
    }

    /**
     * 新增用户
     *
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {

            if (user == null || user.getPassword() == null) {
                return new Result(false, MessageConstant.ADD_USER_PASSWORD_FAIL);
            }

            user.setPassword(encoder.encode(user.getPassword()));

            userService.add(user, roleIds);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    /**
     * 分页条件查询
     *
     * @param queryPageBean 封装的查询条件
     * @return 封装的返回结果
     */
    @RequestMapping(value = "/findPage", method = RequestMethod.POST)
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {

        try {
            PageResult pageResult = userService.findPage(queryPageBean);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, pageResult);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 根据用户id查询用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(int id) {
        try {
            com.itheima.pojo.User user = userService.findById(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 根据userId查询角色的roleIds
     *
     * @return
     */
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(int userId) {
        try {
            List<Integer> roleIds = roleService.findRoleIdsByUserId(userId);
            return new Result(true, MessageConstant.QUERY_ROLE_SUCCESS, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
    }


    /**
     * 更新
     *
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {

            if (user == null || user.getPassword() == null) {
                return new Result(false, MessageConstant.EDIT_USER_PASSWORD_FAIL);
            }

            user.setPassword(encoder.encode(user.getPassword()));

            userService.edit(user, roleIds);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }


    /**
     * 根据id删除用户
     *
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
            return new Result(true, MessageConstant.DELETE_USER_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }

    /**
     * 编辑密码
     *
     * @param map
     * @return
     */
    @RequestMapping("/editPassword")
    public Result editPassword(@RequestBody Map map) {
        try {

            String username = (String) map.get("username");
            String oldPassword = (String) map.get("oldPassword");
            String newPassword = (String) map.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return new Result(false, MessageConstant.EDIT_USER_PASSWORD_FAIL);

            }

            //根据用户名查询
            com.itheima.pojo.User user = userService.findByUsername(username);

            if (!encoder.matches(oldPassword, user.getPassword())) {
                return new Result(false, MessageConstant.EDIT_USERNAME_PASSWORD_FAIL);

            }

            //修改密码
            user.setPassword(encoder.encode(newPassword));

            userService.editPassword(user);
            return new Result(true, MessageConstant.UPDATE_USERNAME_PASSWORD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPDATE_USERNAME_PASSWORD_FAIL);
        }
    }

    /**
     *
     * @return
     */
    @RequestMapping("/getUserRole")
    public Result getUserPerssion(){
        try {
            //1. 获得SecurityContext上下文对象, 获得认证对象, 获得User对象
            org.springframework.security.core.userdetails.User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            List list= userService.getUserRole(username);
            return new Result(true,"Y",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"N");
        }
    }
    @RequestMapping("/changeUserRole")
    public Result changeUserRole(@RequestParam int id){
        try {
            List list= userService.changeUserRole(id);
            return new Result(true,"Y",list);
        } catch (Exception E) {
            E.printStackTrace();
            return new Result(false,"N");
        }
    }
    /**
     * 头像上传
     * @param imgFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        try {
            //1.获得文件名
            String filename = imgFile.getOriginalFilename();
            //2.把文件名替换成UUID文件名
            filename =  UploadUtils.getUUIDName(filename);
            //3.调用工具类进行上传
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),filename);
            //4. 获得SecurityContext上下文对象, 获得认证对象, 获得User对象
            org.springframework.security.core.userdetails.User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            //5.将头像图片名称存入数据库
            userService.updateUserImgByFilename(filename,username);
            return new Result(true, MessageConstant.UserImg_UPLOAD_SUCCESS,filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UserImg_UPLOAD_FAIL);
        }
    }

}


